package com.hp.consumer.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.hp.consumer.service.EchoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author dongxing
 **/
@RestController
@AllArgsConstructor(onConstructor_={@Autowired})
@RequestMapping("/user")
@Slf4j
public class UserController {

//    private final LoadBalancerClient loadBalancerClient;
//    private final RestTemplate restTemplate;
    private final EchoService echoService;


//    @GetMapping("/echo/{id}")
//    @SentinelResource(value ="/test")
//    public Object show(@PathVariable Integer id) {
//        //使用 LoadBalanceClient 和 RestTemolate 结合的方式来访问
//        ServiceInstance serviceInstance = loadBalancerClient.choose("sentinel-provider");
////        List<ServiceInstance> instances = discoveryClient.getInstances("nacos-producer");
//        String url = String.format("http://%s:%s/mapper/config/user/%s",serviceInstance.getHost(),serviceInstance.getPort(),id);
//        System.out.println("request url:"+url);
////        Map<String, Object> map = Maps.newHashMap();
////        map.put("pageNum",1);
////        map.put("pageSize",10);
//        Object forObject = restTemplate.getForObject(url, Object.class);
//        return forObject;
//    }


    @GetMapping("/echo/{id}")
    @SentinelResource(value ="/test",fallback = "testFallback")
    public String echoservice(@PathVariable String id) {
        return this.echoService.echo("------------"+id);
    }


    @GetMapping("/test")
    public String echoserviceTest(@RequestParam String id) {
        return this.echoService.echo("------------"+id);
    }


    // Fallback 函数，函数签名与原函数一致或加一个 Throwable 类型的参数.
    public String testFallback(String id, Throwable ex) {
        log.info("Begin into testFallback ------------"+ex.getMessage());
        return new String("------------失败");
    }

}
